package cn.com.nes.common.util;

import cn.com.nes.site.interceptor.RequestWrapper;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Slf4j
public class OpRequestWrap extends HttpServletRequestWrapper {

	public OpRequestWrap(HttpServletRequest request) throws IOException {
		super(request);
	}

	public boolean checkLetterOrNum(String str) {
		String regEx = "^[A-Za-z0-9_]+$";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.matches();
	}

	private String format(String value) {
		try {
			if (value == null || value.equals("")) {
				return value;
			}

			String[] source_stra = { "ALTER", "CALL", "CREATE", "DELETE",
					"GRANT", "INSERT", "LOAD", "LOCK", "MERGE", "MODIFY",
					"REMOVE", "RENAME", "REPLACE", "REVOKE", "SET", "SELECT",
					"START", "STOP", "USE", "UPDATE", /*"IMG",*/ "HREF", "<SCRIPT",
					" OR", "TRUNCATE", "DROP" };

			String[] dest_stra = { "ＡLTER", "ＣALL", "ＣREATE", "ＤELETE",
					"ＧRANT", "ＩNSERT", "ＬOAD", "ＬOCK", "ＭERGE", "ＭODIFY",
					"ＲEMOVE", "ＲENAME", "ＲEPLACE", "ＲEVOKE", "ＳET", "ＳELECT",
					"ＳTART", "ＳTOP", "ＵSE", "ＵPDATE", /*"ＩMG",*/ "HｒEF", "<ＳCRIPT",
					" OＲ", "TＲUNCATE", "DＲOP" };

			int idx = value.indexOf("\'");
			int idx_json = value.indexOf("{");
			if (idx >= 0 && idx_json < 0) {
				///value = value.replaceAll("\'", "‘");
			}

			idx = value.indexOf("\"");
			if (idx >= 0 && idx_json < 0) {
				///value = value.replaceAll("\"", "”");
			}

			for (int i = 0; i < source_stra.length; i++) {
				idx = value.toUpperCase().indexOf(source_stra[i]);
				if (idx >= 0) {
					idx = idx + source_stra[i].length();
					int len = value.length();
					if (len > idx) {
						char lastKey = value.charAt(idx);
						if (lastKey == '(' || lastKey == '#' || lastKey == ' '
								|| lastKey == '/'|| lastKey == '=') {
							value = value.replaceAll("(?i)" + source_stra[i],
									dest_stra[i]);
						}
					}

					if (source_stra[i].equals("<SCRIPT")) {
						value = value.replaceAll("(?i)" + source_stra[i],
								dest_stra[i]);
					}

				}
			}
		} catch (Exception e) {
		}
		return value;
	}

	public Object getAttribute(String name) {
		Object value = super.getAttribute(name);
		if (value instanceof String) {
			value = format(String.valueOf(value));
		} if( value instanceof java.util.HashMap){
			HashMap map = (HashMap)value;
			for (Object key : map.keySet()) {
				 Object val = map.get(key);
				 if(val instanceof String){
					 val = format(String.valueOf(val));
					 map.put(key, val);
				 }
			}			
		}
		return value;
	}

	/**
	 * 重写getParameter方法
	 * 
	 * @param name
	 * @return
	 */
	public String getParameter(String name) {
		String value = super.getParameter(name);
		if (value == null)
			return null;
		return format(value);
	}

	/**
	 * 
	 * @param name
	 * @return
	 */
	public String[] getParameterValues(String name) {
		String[] values = super.getParameterValues(name);
		if (values != null) {
			for (int i = 0; i < values.length; i++) {
				values[i] = format(values[i]);
			}
		}
		return values;
	}

	/**
	 * @return
	 */
	public Map<String, String[]> getParameterMap() {
		Map<String, String[]> parameterMap = super.getParameterMap();
		HashMap<String, String[]> paramMap = new HashMap<>();
		paramMap.putAll(parameterMap);
		paramMap = (HashMap<String, String[]>) paramMap.clone();
		for (Iterator iterator = paramMap.entrySet().iterator(); iterator
				.hasNext();) {
			Map.Entry<String, String[]> entry = (Map.Entry<String, String[]>) iterator
					.next();
			String[] values = entry.getValue();
			for (int i = 0; i < values.length; i++) {
				if (values[i] instanceof String) {
					values[i] = format(values[i]);
				}
			}
			entry.setValue(values);
		}
		return paramMap;
	}

	public String getBody() throws IOException {
		return ((RequestWrapper) getRequest()).getBody();
	}


}
